<?php

namespace App\Http\Controllers\Admin\Finance\Receivable;

use App\Http\Controllers\Controller;
use App\Http\Requests\airline\base\BanRequest;

use App\Models\airline\base\FlightModel;
use App\Models\examine\RecordDetailModel;
use App\Models\examine\RecordModel;
use App\Models\finance\ReceivableGenericModel;
use App\Models\OrderModel;
use App\Models\RecBillModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class Bill extends Controller
{
    use BanRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);

        $customer_id = $request->input('customer_id', '');



        $query = RecBillModel::query()->with(['customer']);


        if($customer_id){
            $query->where('customer_id', $customer_id);
        }



        $total = $query->count('id');

        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {

            $res = [
                'id' => $item->id,
                'sn' => $item->sn,
                'customer_id' => $item->customer_id,
                'customer_name' => $item->customer->name ?? '',
                'take_order_count' => $item->take_order_count,
                'start' => $item->start,
                'end' => $item->end,
                'amount' => $item->amount,
                'pay_amount' => $item->pay_amount,
                'pay_attachment' => $item->pay_attachment,
                'pay_remark' => $item->pay_remark,
                'status' => $item->status,
                'status_text' => RecBillModel::BILL_STATUS_MAPS[$item->status] ?? '',
                'invoice_file' => $item->invoice_file,
                'created_at' => $item->created_at->format('Y-m-d H:i:s')
            ];
            return $res;
        });


        return $this->success(['list' => $list, 'total' => $total]);
    }

    //删除
    public function delete(Request $request, $id) {
        $rec_bill = RecBillModel::find($id);
        if (!$rec_bill) {
            return $this->error('数据不存在');
        }

        ReceivableGenericModel::where('bill_id', $id)->update ([
            'bill_id' => null,
        ]);

        $rec_bill->delete();
        return $this->success();
    }



    public function detail(Request $request) {
        $id = $request->input('id');
        $rec_bill = RecBillModel::find($id);
        if (!$rec_bill) {
            return $this->error('数据不存在');
        }

        $receiv_take_orders = ReceivableGenericModel::with(['take_order', 'detail', 'flight'])->where('bill_id', $id)->get();

        $base_head = [
            ['label' => '提单号', 'prop' => 'take_order_sn'],
            ['label' => '货物属性', 'prop' => 'goods_attr'],
            ['label' => '航班日期', 'prop' => 'flight_date'],
            ['label' => '航班号', 'prop' => 'flight_number'],
            ['label' => '客户名称', 'prop' => 'customer_name'],
            ['label' => '起运地', 'prop' => 'origin'],
            ['label' => '目的地', 'prop' => 'destination'],
            ['label' => '件数', 'prop' => 'package_num'],
            ['label' => '毛重', 'prop' => 'gross_weight'],
            ['label' => '体积重', 'prop' => 'volume_weight'],
            ['label' => '计费重', 'prop' => 'charging_weight'],
            ['label' => '空运单价', 'prop' => 'price'],
        ];

        $detail_name = [];
        foreach ($receiv_take_orders as $key => $value){
            if(count($value->detail)){
                $detail_name = array_merge($detail_name, $value->detail->pluck('name')->toArray());
            }
        }

        $detail_name = array_unique($detail_name);

        $detail_arr = [];
        foreach ($detail_name as $key => $value){
            $prop = 'fee' . $key;
            $base_head[] = [
                'label' => $value,
                'prop' => $prop
            ];
            $detail_arr[$value] = $prop;
        }

        $base_head[] = [
            'label' => '总金额',
            'prop' => 'total_amount'
        ];

        $list = $receiv_take_orders->map(function($item) use ($detail_arr) {
            $origin = $item->flight?->start_port_code;
            $destination = $item->flight?->arrive_port_code;

            $flight_number_id = $item->flight?->items?->first()->airline_flight_id ?? '';
            if(!$flight_number_id){
                $flight_number = '';
            }else{
                $flight_number = FlightModel::where('id', $flight_number_id)->value('flight_number') ?? '';
            }

            $flight_date = $item->flight->take_off_time ? date('Y-m-d', strtotime($item->flight->take_off_time)) : '';

            $res = [
                'take_order_sn' => $item->take_order->sn ??  '',
                'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$item->take_order->goods_attr ?? ''] ?? '',
                'flight_date' => $flight_date,
                'flight_number' => $flight_number,
                'customer_name' => $item->take_order->customer->name ?? '',
                'origin' => $origin,
                'destination' => $destination,
                'package_num' => $item->package_num,
                'gross_weight' => $item->gross_weight,
                'volume_weight' => $item->volume_weight,
                'charging_weight' => $item->charging_weight,
                'price' => $item->air_freight_unit_price,
                'total_amount' => $item->detail->sum('amount') ?? 0,
            ];

            $item->detail->map(function($item2) use ($detail_arr, &$res) {
                $res[$detail_arr[$item2->name]] = $item2->amount;
            });

            return $res;
        });

        $res = [
            'head' => $base_head,
            'list' => $list
        ];
        return $this->success($res);
    }

    public function examine(Request $request, $id) {
        $params = $request->all();
        $validator = Validator::make($params, [
            'status' => 'required|integer|in:2,3'
        ], [
            'status.required' => '请选择审核结果',
            'status.in' => '审核结果不在范围内',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $rec_bill = RecBillModel::find($id);
        if (!$rec_bill) {
            return $this->error('数据不存在');
        }

        if($rec_bill->status != 1)  {
            return $this->error('账单不是待审核状态');
        }

        $record = RecordModel::find($rec_bill->examine_record_id);
        if(!$record){
            return $this->error('数据不存在');
        }

        $auth = $request->get('auth');
        DB::beginTransaction();
        try {
            RecordDetailModel::where('record_id', $record->id)
                ->where('admin_id', $auth->id)
                ->update([
                    'status' => 2,
                    'examine_time' => date('Y-m-d H:i:s')
                ]);

            $record_pass = false;
            switch ($record->examine_type) {
                case 1:  //依次审批
                    $find_next = RecordDetailModel::where('record_id', $record->record_id)
                        ->where('is_examine', 0)
                        ->orderBy('sort')
                        ->first();
                    if($find_next){
                        $find_next->is_examine = 1;
                        $find_next->save();
                    } else {
                        $record_pass = true;
                    }
                    break;
                case 2:
                    $record_pass = true;
                    break;
                case 3:
                    $find_else = RecordDetailModel::where('record_id', $record->record_id)
                        ->where('status', 1)->first();
                    if(!$find_else){
                        $record_pass = true;

                    }
                    break;
            }

            if($record_pass){
                $record->status = 2;
                $record->save();

                $rec_bill->status = 2;
                $rec_bill->save();
            }else{
                $rec_bill->status = 3;
                $rec_bill->save();
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }


    //发送账单
    public function send($id) {
        $bill = RecBillModel::find($id);
        if(!$bill) {
            return $this->error('账单不存在');
        }

        if($bill->status != 2) {
            return $this->error('账单状态不正确');
        }

        $bill->status = RecBillModel::BILL_WAIT_CONFIRM;
        $bill->save();

        return $this->success();
    }

    //确认核销收款
    public function confirm(Request $request, $id) {
        $bill = RecBillModel::find($id);
        if(!$bill) {
            return $this->error('账单不存在');
        }

        if($bill->status != RecBillModel::BILL_PAID) {
            return $this->error('账单状态不正确');
        }

        $bill->status = RecBillModel::BILL_WRITE_OFF;
        $bill->save();

        return $this->success();

    }

    public function invoice(Request $request) {
        $id = $request->input('id');
        $invoice = $request->input('invoice_file',  '');

        $bill = RecBillModel::find($id);
        if(!$bill) {
            return $this->error('账单不存在');
        }

        $bill->invoice_file = $invoice;
        $bill->save();

        return $this->success();

    }




}
